package com.city.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.city.eduservice.entity.EduSubject;
import com.city.eduservice.entity.excel.SubjectData;
import com.city.eduservice.entity.subject.OneSubject;
import com.city.eduservice.entity.subject.TwoSubject;
import com.city.eduservice.listener.SubjectExcelListener;
import com.city.eduservice.mapper.EduSubjectMapper;
import com.city.eduservice.service.EduSubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author city
 * @since 2020-06-18
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        List<OneSubject> oneSubjectLists=new ArrayList<>();


        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();
        eduSubjectQueryWrapper.eq("parent_id","0");
        //mybatispuls生成的service中可以直接操作数据库，因为接口继承了mapper，统为baseMapper或者this，因为这个类也继承了basemapper
        List<EduSubject> oneSubjectList = baseMapper.selectList(eduSubjectQueryWrapper);

        //查询2级分类
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("parent_id","0");
        List<EduSubject> twoSubjects = this.list(queryWrapper);

        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            /*OneSubject.setTitle(eduSubject.getTitle());
            OneSubject.setId(eduSubject.getId());*/

            BeanUtils.copyProperties(eduSubject,oneSubject);//对象属性赋值

            List<TwoSubject> twoSubjectsList=new ArrayList<>();
            //设置一级分类的二级分类
            for (EduSubject twoSubject : twoSubjects) {
                if (twoSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject1 = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject,twoSubject1);
                    twoSubjectsList.add(twoSubject1);
                }
            }
            oneSubject.setChildren(twoSubjectsList);
            oneSubjectLists.add(oneSubject);
        }

        return oneSubjectLists;
    }
}
